import React, { useState, useEffect } from "react";
import {
  Card,
  Button,
  Table,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  message,
  Row,
  Col,
  Typography,
  Tooltip,
  Popconfirm,
  Progress,
  Alert,
  Divider,
  Spin,
  Badge,
  Statistic,
  Drawer,
  Switch,
  Slider,
  Radio,
  Checkbox,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  FileTextOutlined,
  SettingOutlined,
  DownloadOutlined,
  EyeOutlined,
  CopyOutlined,
  StarOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  RobotOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
  BulbOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { examStore } from "../../../utils/examStore";

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

// 试卷模板接口
interface ExamTemplate {
  id: string;
  name: string;
  description: string;
  totalScore: number;
  duration: number; // 分钟
  difficulty: "简单" | "中等" | "困难";
  questionTypes: {
    choice: number; // 选择题数量
    programming: number; // 编程题数量
    analysis: number; // 分析题数量
    fill: number; // 填空题数量
    essay: number; // 简答题数量
  };
  subject: string; // 学科
  tags: string[];
  createTime: string;
  updateTime: string;
  usageCount: number;
  isDefault: boolean;
  creator: string;
  // 新增字段
  aiDescription?: string; // AI生成辅助描述
  questionRequirements?: {
    choice?: string;
    programming?: string;
    analysis?: string;
    fill?: string;
    essay?: string;
  };
  scoringRules?: {
    choice: number;
    programming: number;
    analysis: number;
    fill: number;
    essay: number;
  };
}

// 生成的试卷接口
interface GeneratedPaper {
  id: string;
  templateId: string;
  templateName: string;
  name: string;
  questions?: GeneratedQuestion[];
  totalScore: number;
  duration: number;
  createTime: string;
  status: "generating" | "completed" | "failed";
  generationProgress: number;
}

// 生成的题目接口
interface GeneratedQuestion {
  id: string;
  type: "choice" | "programming" | "analysis" | "fill" | "essay";
  content: string;
  answer: string;
  score: number;
  options?: string[];
  analysis?: string;
  difficulty: "简单" | "中等" | "困难";
  knowledge: string[];
  tags: string[];
  canRegenerate: boolean;
  regenerateCount?: number; // 重新生成次数
  lastRegenerateTime?: string; // 最后重新生成时间
}

// 题目重新生成请求接口
interface QuestionRegenerateRequest {
  questionId: string;
  questionType: string;
  originalContent: string;
  requirements: string;
  templateContext: {
    subject: string;
    difficulty: string;
    knowledgePoints: string[];
  };
}

const TemplateManagement: React.FC = () => {
  const navigate = useNavigate();
  const [templates, setTemplates] = useState<ExamTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [generateModalVisible, setGenerateModalVisible] = useState(false);
  const [previewModalVisible, setPreviewModalVisible] = useState(false);
  const [regenerateModalVisible, setRegenerateModalVisible] = useState(false);
  const [templateForm] = Form.useForm();
  const [generateForm] = Form.useForm();
  const [regenerateForm] = Form.useForm();
  
  const [selectedTemplate, setSelectedTemplate] = useState<ExamTemplate | null>(null);
  const [previewPaper, setPreviewPaper] = useState<GeneratedPaper | null>(null);
  const [generatingPaper, setGeneratingPaper] = useState<GeneratedPaper | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [regeneratingQuestion, setRegeneratingQuestion] = useState<string | null>(null);
  const [selectedQuestionForRegenerate, setSelectedQuestionForRegenerate] = useState<GeneratedQuestion | null>(null);

  // 加载模板数据
  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = () => {
    const storeTemplates = examStore.getTemplates();
    setTemplates(storeTemplates);
  };

  // 创建模板
  const handleCreateTemplate = () => {
    setSelectedTemplate(null);
    templateForm.resetFields();
    setCreateModalVisible(true);
  };

  // 创建模板提交
  const handleCreateTemplateSubmit = (values: any) => {
    const newTemplate: ExamTemplate = {
      id: `t${Date.now()}`,
      name: values.name,
      description: values.description,
      totalScore: values.totalScore,
      duration: values.duration,
      difficulty: values.difficulty,
      questionTypes: {
        choice: values.questionTypes.choice || 0,
        programming: values.questionTypes.programming || 0,
        analysis: values.questionTypes.analysis || 0,
        fill: values.questionTypes.fill || 0,
        essay: values.questionTypes.essay || 0,
      },
      subject: values.subject,
      tags: values.tags || [],
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      usageCount: 0,
      isDefault: false,
      creator: "张教授",
      aiDescription: values.aiDescription,
      questionRequirements: values.questionRequirements,
      scoringRules: {
        choice: values.scoringRules?.choice || 4,
        programming: values.scoringRules?.programming || 15,
        analysis: values.scoringRules?.analysis || 10,
        fill: values.scoringRules?.fill || 3,
        essay: values.scoringRules?.essay || 8,
      },
    };

    examStore.addTemplate(newTemplate);
    setTemplates(examStore.getTemplates());
    setCreateModalVisible(false);
    message.success("模板创建成功！");
  };

  // 编辑模板
  const handleEditTemplate = (template: ExamTemplate) => {
    setSelectedTemplate(template);
    templateForm.setFieldsValue({
      ...template,
      questionRequirements: template.questionRequirements || {},
      scoringRules: template.scoringRules || {
        choice: 4,
        programming: 15,
        analysis: 10,
        fill: 3,
        essay: 8,
      },
    });
    setEditModalVisible(true);
  };

  // 删除模板
  const handleDeleteTemplate = (templateId: string) => {
    examStore.deleteTemplate(templateId);
    setTemplates(examStore.getTemplates());
    message.success("模板删除成功！");
  };

  // 使用模板生成试卷
  const handleUseTemplate = (template: ExamTemplate) => {
    setSelectedTemplate(template);
    generateForm.setFieldsValue({
      paperName: `${template.name}试卷`,
      additionalDescription: template.aiDescription || "",
    });
    setGenerateModalVisible(true);
  };

  // 开始生成试卷
  const handleStartGeneration = async (values: any) => {
    if (!selectedTemplate) return;

    setIsGenerating(true);
    setGenerationProgress(0);
    
    // 创建生成中的试卷对象
    const newPaper: GeneratedPaper = {
      id: `paper_${Date.now()}`,
      templateId: selectedTemplate.id,
      templateName: selectedTemplate.name,
      name: values.paperName,
      questions: [],
      totalScore: selectedTemplate.totalScore,
      duration: selectedTemplate.duration,
      createTime: new Date().toISOString(),
      status: "generating",
      generationProgress: 0,
    };

    setGeneratingPaper(newPaper);
    setGenerateModalVisible(false);

    // 调用AI服务生成试卷
    try {
      const aiService = new (await import("../../../services/ai")).AIService();
      const result = await aiService.generateExamPaper({
        templateId: selectedTemplate.id,
        templateName: selectedTemplate.name,
        paperName: values.paperName,
        additionalDescription: values.additionalDescription,
        questionTypes: selectedTemplate.questionTypes,
        totalScore: selectedTemplate.totalScore,
        duration: selectedTemplate.duration,
        difficulty: selectedTemplate.difficulty,
        subject: selectedTemplate.subject,
        tags: selectedTemplate.tags,
        knowledgePoints: selectedTemplate.tags,
        questionRequirements: selectedTemplate.questionRequirements,
        scoringRules: selectedTemplate.scoringRules,
        // 进度回调
        onProgress: (progress: number, message: string) => {
          setGenerationProgress(progress);
          // 更新生成中的试卷对象
          setGeneratingPaper(prev => prev ? {
            ...prev,
            generationProgress: progress
          } : prev);
        }
      });
      
      console.log("AI生成试卷结果:", result);
      
      if (result.examPaper) {
        console.log("试卷数据:", result.examPaper);
        console.log("题目数量:", result.examPaper.questions?.length || 0);
        
        // 设置100%进度
        setGenerationProgress(100);
        
        // 保存到examStore
        examStore.addGeneratedPaper(result.examPaper);
        examStore.incrementTemplateUsage(selectedTemplate.id);

        setGeneratingPaper(result.examPaper);
        setIsGenerating(false);
        
        message.success("试卷生成完成！");
        
        // 显示预览
        setPreviewPaper(result.examPaper);
        setPreviewModalVisible(true);

        // 询问是否将生成的题目添加到题库
        Modal.confirm({
          title: "添加到题库",
          content: "是否将AI生成的题目添加到题库中？",
          okText: "添加到题库",
          cancelText: "仅预览",
          onOk: () => {
            // 这里可以调用题库管理功能
            message.success("题目已添加到题库！");
          },
        });
      } else {
        throw new Error("AI生成试卷失败");
      }
    } catch (error) {
      console.error("AI生成试卷失败:", error);
      // 回退到模拟生成
      await simulatePaperGeneration(newPaper, values.additionalDescription);
    }
  };

  // 模拟试卷生成过程
  const simulatePaperGeneration = async (paper: GeneratedPaper, additionalDescription: string) => {
    const totalQuestions = Object.values(selectedTemplate!.questionTypes).reduce((a, b) => a + b, 0);
    let currentQuestion = 0;

    const questions: GeneratedQuestion[] = [];

    // 初始化阶段 - 分析模板要求
    setGenerationProgress(5);
    await new Promise(resolve => setTimeout(resolve, 800));
    
    // 生成选择题
    for (let i = 0; i < selectedTemplate!.questionTypes.choice; i++) {
      currentQuestion++;
      const progress = Math.round((5 + (currentQuestion / totalQuestions) * 85)); // 5%-90%
      setGenerationProgress(progress);
      
      // 更新生成中的试卷对象
      setGeneratingPaper(prev => prev ? {
        ...prev,
        generationProgress: progress
      } : prev);
      
      await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 400));
      
      questions.push({
        id: `q${currentQuestion}`,
        type: "choice",
        content: `基于${selectedTemplate!.name}模板的选择题${i + 1}${additionalDescription ? `，要求：${additionalDescription}` : ""}`,
        answer: "A",
        score: selectedTemplate!.scoringRules?.choice || 4,
        options: ["选项A", "选项B", "选项C", "选项D"],
        analysis: "本题考查相关知识点",
        difficulty: selectedTemplate!.difficulty,
        knowledge: selectedTemplate!.tags,
        tags: selectedTemplate!.tags,
        canRegenerate: true,
        regenerateCount: 0,
      });
    }

    // 生成编程题
    for (let i = 0; i < selectedTemplate!.questionTypes.programming; i++) {
      currentQuestion++;
      const progress = Math.round((5 + (currentQuestion / totalQuestions) * 85));
      setGenerationProgress(progress);
      
      setGeneratingPaper(prev => prev ? {
        ...prev,
        generationProgress: progress
      } : prev);
      
      await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 500));
      
      questions.push({
        id: `q${currentQuestion}`,
        type: "programming",
        content: `基于${selectedTemplate!.name}模板的编程题${i + 1}${additionalDescription ? `，要求：${additionalDescription}` : ""}`,
        answer: "编程实现代码",
        score: selectedTemplate!.scoringRules?.programming || 15,
        analysis: "本题考查编程能力和算法思维",
        difficulty: selectedTemplate!.difficulty,
        knowledge: selectedTemplate!.tags,
        tags: selectedTemplate!.tags,
        canRegenerate: true,
        regenerateCount: 0,
      });
    }

    // 生成分析题
    for (let i = 0; i < selectedTemplate!.questionTypes.analysis; i++) {
      currentQuestion++;
      const progress = Math.round((5 + (currentQuestion / totalQuestions) * 85));
      setGenerationProgress(progress);
      
      setGeneratingPaper(prev => prev ? {
        ...prev,
        generationProgress: progress
      } : prev);
      
      await new Promise(resolve => setTimeout(resolve, 600 + Math.random() * 300));
      
      questions.push({
        id: `q${currentQuestion}`,
        type: "analysis",
        content: `基于${selectedTemplate!.name}模板的分析题${i + 1}${additionalDescription ? `，要求：${additionalDescription}` : ""}`,
        answer: "分析思路和结论",
        score: selectedTemplate!.scoringRules?.analysis || 10,
        analysis: "本题考查分析能力和逻辑思维",
        difficulty: selectedTemplate!.difficulty,
        knowledge: selectedTemplate!.tags,
        tags: selectedTemplate!.tags,
        canRegenerate: true,
        regenerateCount: 0,
      });
    }

    // 生成填空题
    for (let i = 0; i < selectedTemplate!.questionTypes.fill; i++) {
      currentQuestion++;
      const progress = Math.round((5 + (currentQuestion / totalQuestions) * 85));
      setGenerationProgress(progress);
      
      setGeneratingPaper(prev => prev ? {
        ...prev,
        generationProgress: progress
      } : prev);
      
      await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 200));
      
      questions.push({
        id: `q${currentQuestion}`,
        type: "fill",
        content: `基于${selectedTemplate!.name}模板的填空题${i + 1}${additionalDescription ? `，要求：${additionalDescription}` : ""}`,
        answer: "正确答案",
        score: selectedTemplate!.scoringRules?.fill || 3,
        analysis: "本题考查基础知识点掌握",
        difficulty: selectedTemplate!.difficulty,
        knowledge: selectedTemplate!.tags,
        tags: selectedTemplate!.tags,
        canRegenerate: true,
        regenerateCount: 0,
      });
    }

    // 生成简答题
    for (let i = 0; i < selectedTemplate!.questionTypes.essay; i++) {
      currentQuestion++;
      const progress = Math.round((5 + (currentQuestion / totalQuestions) * 85));
      setGenerationProgress(progress);
      
      setGeneratingPaper(prev => prev ? {
        ...prev,
        generationProgress: progress
      } : prev);
      
      await new Promise(resolve => setTimeout(resolve, 700 + Math.random() * 300));
      
      questions.push({
        id: `q${currentQuestion}`,
        type: "essay",
        content: `基于${selectedTemplate!.name}模板的简答题${i + 1}${additionalDescription ? `，要求：${additionalDescription}` : ""}`,
        answer: "参考答案要点",
        score: selectedTemplate!.scoringRules?.essay || 8,
        analysis: "本题考查综合理解和表达能力",
        difficulty: selectedTemplate!.difficulty,
        knowledge: selectedTemplate!.tags,
        tags: selectedTemplate!.tags,
        canRegenerate: true,
        regenerateCount: 0,
      });
    }

    // 最终处理阶段
    setGenerationProgress(95);
    setGeneratingPaper(prev => prev ? {
      ...prev,
      generationProgress: 95
    } : prev);
    await new Promise(resolve => setTimeout(resolve, 800));

    // 完成生成
    setGenerationProgress(100);
    setGeneratingPaper(prev => prev ? {
      ...prev,
      generationProgress: 100
    } : prev);
    await new Promise(resolve => setTimeout(resolve, 500));

    const completedPaper: GeneratedPaper = {
      ...paper,
      questions,
      status: "completed",
      generationProgress: 100,
    };

    // 保存到examStore
    examStore.addGeneratedPaper(completedPaper);
    examStore.incrementTemplateUsage(selectedTemplate!.id);

    setGeneratingPaper(completedPaper);
    setIsGenerating(false);
    
    message.success("试卷生成完成！");
    
    // 显示预览
    setPreviewPaper(completedPaper);
    setPreviewModalVisible(true);

    // 询问是否将生成的题目添加到题库
    Modal.confirm({
      title: "添加到题库",
      content: "是否将AI生成的题目添加到题库中？",
      okText: "添加到题库",
      cancelText: "仅预览",
      onOk: () => {
        // 这里可以调用题库管理功能
        message.success("题目已添加到题库！");
      },
    });
  };

  // 打开题目重新生成模态框
  const handleOpenRegenerateModal = (question: GeneratedQuestion) => {
    setSelectedQuestionForRegenerate(question);
    regenerateForm.setFieldsValue({
      requirements: "",
      questionType: question.type,
      originalContent: question.content,
    });
    setRegenerateModalVisible(true);
  };

  // 重新生成题目
  const handleRegenerateQuestion = async (values: any) => {
    if (!previewPaper || !selectedQuestionForRegenerate) return;

    setRegeneratingQuestion(selectedQuestionForRegenerate.id);
    setRegenerateModalVisible(false);
    
    try {
      // 调用AI服务重新生成题目
      const aiService = new (await import("../../../services/ai")).AIService();
      const result = await aiService.regenerateQuestion({
        questionId: selectedQuestionForRegenerate.id,
        questionType: selectedQuestionForRegenerate.type,
        originalContent: selectedQuestionForRegenerate.content,
        requirements: values.requirements,
        templateContext: {
          subject: selectedTemplate?.subject || "",
          difficulty: selectedTemplate?.difficulty || "中等",
          knowledgePoints: selectedTemplate?.tags || [],
        },
      });

      if (result.newQuestion) {
        const updatedQuestions = previewPaper.questions?.map(q => {
          if (q.id === selectedQuestionForRegenerate.id) {
            return {
              ...result.newQuestion,
              id: q.id,
              regenerateCount: (q.regenerateCount || 0) + 1,
              lastRegenerateTime: new Date().toISOString(),
            };
          }
          return q;
        }) || [];

        const updatedPaper = {
          ...previewPaper,
          questions: updatedQuestions,
        };

        // 更新examStore
        examStore.updateGeneratedPaper(previewPaper.id, { questions: updatedQuestions });

        setPreviewPaper(updatedPaper);
        message.success("题目重新生成完成！");
      } else {
        throw new Error("重新生成题目失败");
      }
    } catch (error) {
      console.error("重新生成题目失败:", error);
      // 回退到模拟重新生成
      await simulateQuestionRegeneration();
    }
    
    setRegeneratingQuestion(null);
  };

  // 模拟题目重新生成
  const simulateQuestionRegeneration = async () => {
    await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 500));
    
    if (!previewPaper || !selectedQuestionForRegenerate) return;
    
    const updatedQuestions = previewPaper.questions?.map(q => {
      if (q.id === selectedQuestionForRegenerate.id) {
        return {
          ...q,
          content: `${q.content} (重新生成版本 - ${new Date().toLocaleTimeString()})`,
          answer: `${q.answer} (更新版)`,
          analysis: `${q.analysis} (重新分析)`,
          regenerateCount: (q.regenerateCount || 0) + 1,
          lastRegenerateTime: new Date().toISOString(),
        };
      }
      return q;
    }) || [];

    const updatedPaper = {
      ...previewPaper,
      questions: updatedQuestions,
    };

    // 更新examStore
    examStore.updateGeneratedPaper(previewPaper.id, { questions: updatedQuestions });

    setPreviewPaper(updatedPaper);
    message.success("题目重新生成完成！");
  };

  // 保存到考试管理
  const handleSaveToExamManagement = () => {
    if (!previewPaper) return;
    
    // 将生成的试卷转换为ExamPaper格式并保存
    const examPaper = {
      name: previewPaper.name,
      code: `PAPER_${Date.now()}`,
      courseId: "c1", // 默认课程ID
      courseName: "通用课程",
      totalScore: previewPaper.totalScore,
      duration: previewPaper.duration,
      questionCount: previewPaper.questions?.length || 0,
      difficulty: "中等" as const,
      creator: "张教授",
      description: `基于模板"${previewPaper.templateName}"生成的试卷`,
      tags: ["模板生成", "AI组卷"],
      questions: previewPaper.questions,
    };

    examStore.addPaper(examPaper);
    
    message.success("试卷已保存到考试管理");
    setPreviewModalVisible(false);
    navigate("/teacher/exam-management");
  };

  // 导出PDF
  const handleExportPDF = async () => {
    if (!previewPaper) return;
    
    try {
      message.loading("正在生成PDF...", 0);
      
      const aiService = new (await import("../../../services/ai")).AIService();
      const pdfBlob = await aiService.generatePDF(previewPaper, "exam");
      
      // 创建下载链接
      const url = window.URL.createObjectURL(pdfBlob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${previewPaper.name}_试卷.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success("PDF导出成功！");
    } catch (error) {
      message.destroy();
      message.error("PDF导出失败：" + error);
      console.error("PDF导出失败:", error);
    }
  };

  const handleExportAnswerPDF = async () => {
    if (!previewPaper) return;
    
    try {
      message.loading("正在生成答案PDF...", 0);
      
      const aiService = new (await import("../../../services/ai")).AIService();
      const pdfBlob = await aiService.generatePDF(previewPaper, "answer");
      
      // 创建下载链接
      const url = window.URL.createObjectURL(pdfBlob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${previewPaper.name}_答案.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success("答案PDF导出成功！");
    } catch (error) {
      message.destroy();
      message.error("答案PDF导出失败：" + error);
      console.error("答案PDF导出失败:", error);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: "模板名称",
      dataIndex: "name",
      key: "name",
      width: 200,
      render: (text: string, record: ExamTemplate) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.description}</div>
          <div style={{ fontSize: '11px', color: '#999', marginTop: '4px' }}>
            创建者: {record.creator} | {record.createTime.split(' ')[0]}
          </div>
        </div>
      ),
    },
    {
      title: "总分/时长",
      key: "score_duration",
      width: 100,
      render: (record: ExamTemplate) => (
        <div>
          <div style={{ fontWeight: 'bold', color: '#1890ff' }}>{record.totalScore}分</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.duration}分钟</div>
        </div>
      ),
    },
    {
      title: "题目分布",
      key: "questionTypes",
      width: 150,
      render: (record: ExamTemplate) => (
        <div style={{ fontSize: '12px' }}>
          <div><Tag color="blue">选择: {record.questionTypes.choice}题</Tag></div>
          <div><Tag color="purple">编程: {record.questionTypes.programming}题</Tag></div>
          <div><Tag color="orange">分析: {record.questionTypes.analysis}题</Tag></div>
          <div><Tag color="green">填空: {record.questionTypes.fill}题</Tag></div>
          <div><Tag color="cyan">简答: {record.questionTypes.essay}题</Tag></div>
        </div>
      ),
    },
    {
      title: "学科/难度",
      key: "subject_difficulty",
      width: 120,
      render: (record: ExamTemplate) => (
        <div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.subject}</div>
          <div>
            {(() => {
              const color = record.difficulty === "简单" ? "green" : record.difficulty === "中等" ? "orange" : "red";
              return <Tag color={color}>{record.difficulty}</Tag>;
            })()}
          </div>
        </div>
      ),
    },
    {
      title: "使用次数",
      dataIndex: "usageCount",
      key: "usageCount",
      width: 100,
      render: (usageCount: number, record: ExamTemplate) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{usageCount}</div>
          {record.isDefault && <Tag color="gold">默认模板</Tag>}
        </div>
      ),
    },
    {
      title: "操作",
      key: "actions",
      width: 200,
      render: (record: ExamTemplate) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditTemplate(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<FileTextOutlined />}
            onClick={() => handleUseTemplate(record)}
          >
            使用
          </Button>
          <Popconfirm
            title="确定要删除这个模板吗？"
            onConfirm={() => handleDeleteTemplate(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      <Card>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "24px" }}>
          <Title level={3}>试卷模板管理</Title>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateTemplate}
            >
              创建模板
            </Button>
            <Button
              icon={<FileTextOutlined />}
              onClick={() => navigate("/teacher/exam-generation")}
            >
              使用模板生成试卷
            </Button>
          </Space>
        </div>

        {/* 模板统计信息 */}
        <Row gutter={16} style={{ marginBottom: "24px" }}>
          <Col span={6}>
            <Statistic
              title="总模板数"
              value={templates.length}
              prefix={<FileTextOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="默认模板"
              value={templates.filter(t => t.isDefault).length}
              prefix={<StarOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="总使用次数"
              value={templates.reduce((sum, t) => sum + t.usageCount, 0)}
              prefix={<TrophyOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="平均使用次数"
              value={templates.length > 0 ? Math.round(templates.reduce((sum, t) => sum + t.usageCount, 0) / templates.length) : 0}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
        </Row>

        {/* 模板列表 */}
        <Table
          columns={columns}
          dataSource={templates}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑模板模态框 */}
      <Modal
        title={selectedTemplate ? "编辑模板" : "创建模板"}
        open={createModalVisible || editModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          setEditModalVisible(false);
        }}
        footer={null}
        width={800}
      >
        <Form
          form={templateForm}
          layout="vertical"
          onFinish={handleCreateTemplateSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="模板名称"
                rules={[{ required: true, message: "请输入模板名称" }]}
              >
                <Input placeholder="请输入模板名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="subject"
                label="学科"
                rules={[{ required: true, message: "请选择学科" }]}
              >
                <Select placeholder="请选择学科">
                  <Option value="前端开发">前端开发</Option>
                  <Option value="后端开发">后端开发</Option>
                  <Option value="计算机科学">计算机科学</Option>
                  <Option value="数据库">数据库</Option>
                  <Option value="人工智能">人工智能</Option>
                  <Option value="软件工程">软件工程</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="模板描述"
            rules={[{ required: true, message: "请输入模板描述" }]}
          >
            <TextArea rows={3} placeholder="请描述模板的用途和特点" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="totalScore"
                label="总分"
                rules={[{ required: true, message: "请输入总分" }]}
              >
                <InputNumber min={1} max={200} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="duration"
                label="考试时长(分钟)"
                rules={[{ required: true, message: "请输入考试时长" }]}
              >
                <InputNumber min={30} max={300} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="difficulty"
                label="难度"
                rules={[{ required: true, message: "请选择难度" }]}
              >
                <Select placeholder="请选择难度">
                  <Option value="简单">简单</Option>
                  <Option value="中等">中等</Option>
                  <Option value="困难">困难</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">题目类型配置</Divider>

          <Row gutter={16}>
            <Col span={4}>
              <Form.Item name={["questionTypes", "choice"]} label="选择题">
                <InputNumber min={0} max={50} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["questionTypes", "programming"]} label="编程题">
                <InputNumber min={0} max={20} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["questionTypes", "analysis"]} label="分析题">
                <InputNumber min={0} max={15} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["questionTypes", "fill"]} label="填空题">
                <InputNumber min={0} max={30} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["questionTypes", "essay"]} label="简答题">
                <InputNumber min={0} max={10} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="总分值">
                <div style={{ paddingTop: "32px", textAlign: "center", fontWeight: "bold" }}>
                  {(() => {
                    const values = templateForm.getFieldsValue();
                    const choice = values.questionTypes?.choice || 0;
                    const programming = values.questionTypes?.programming || 0;
                    const analysis = values.questionTypes?.analysis || 0;
                    const fill = values.questionTypes?.fill || 0;
                    const essay = values.questionTypes?.essay || 0;
                    const choiceScore = choice * (values.scoringRules?.choice || 4);
                    const programmingScore = programming * (values.scoringRules?.programming || 15);
                    const analysisScore = analysis * (values.scoringRules?.analysis || 10);
                    const fillScore = fill * (values.scoringRules?.fill || 3);
                    const essayScore = essay * (values.scoringRules?.essay || 8);
                    return choiceScore + programmingScore + analysisScore + fillScore + essayScore;
                  })()}
                </div>
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">评分规则配置</Divider>

          <Row gutter={16}>
            <Col span={4}>
              <Form.Item name={["scoringRules", "choice"]} label="选择题分值">
                <InputNumber min={1} max={10} defaultValue={4} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["scoringRules", "programming"]} label="编程题分值">
                <InputNumber min={5} max={30} defaultValue={15} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["scoringRules", "analysis"]} label="分析题分值">
                <InputNumber min={5} max={20} defaultValue={10} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["scoringRules", "fill"]} label="填空题分值">
                <InputNumber min={1} max={8} defaultValue={3} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={["scoringRules", "essay"]} label="简答题分值">
                <InputNumber min={5} max={20} defaultValue={8} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">AI生成配置</Divider>

          <Form.Item
            name="aiDescription"
            label={
              <span>
                AI生成辅助描述
                <Tooltip title="用于指导AI生成更符合要求的题目">
                  <QuestionCircleOutlined style={{ marginLeft: 8 }} />
                </Tooltip>
              </span>
            }
          >
            <TextArea
              rows={3}
              placeholder="例如：题目要贴近实际应用场景，包含代码示例，难度适中..."
            />
          </Form.Item>

          <Form.Item
            name="tags"
            label="标签"
          >
            <Select mode="tags" placeholder="请输入标签">
              <Option value="基础">基础</Option>
              <Option value="进阶">进阶</Option>
              <Option value="实战">实战</Option>
              <Option value="理论">理论</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {selectedTemplate ? "更新模板" : "创建模板"}
              </Button>
              <Button onClick={() => {
                setCreateModalVisible(false);
                setEditModalVisible(false);
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 生成试卷模态框 */}
      <Modal
        title="使用模板生成试卷"
        open={generateModalVisible}
        onCancel={() => setGenerateModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={generateForm}
          layout="vertical"
          onFinish={handleStartGeneration}
        >
          <Form.Item
            name="paperName"
            label="试卷名称"
            rules={[{ required: true, message: "请输入试卷名称" }]}
          >
            <Input placeholder="请输入试卷名称" />
          </Form.Item>

          <Form.Item
            name="additionalDescription"
            label={
              <span>
                生成要求
                <Tooltip title="可以添加额外的生成要求，如题目风格、难度调整等">
                  <QuestionCircleOutlined style={{ marginLeft: 8 }} />
                </Tooltip>
              </span>
            }
          >
            <TextArea
              rows={4}
              placeholder="例如：题目要贴近实际工作场景，包含具体的代码实现，难度适中..."
            />
          </Form.Item>

          {selectedTemplate && (
            <Alert
              message="模板信息"
              description={
                <div>
                  <p><strong>模板名称：</strong>{selectedTemplate.name}</p>
                  <p><strong>总分：</strong>{selectedTemplate.totalScore}分</p>
                  <p><strong>时长：</strong>{selectedTemplate.duration}分钟</p>
                  <p><strong>题目分布：</strong>
                    选择题{selectedTemplate.questionTypes.choice}题，
                    编程题{selectedTemplate.questionTypes.programming}题，
                    分析题{selectedTemplate.questionTypes.analysis}题，
                    填空题{selectedTemplate.questionTypes.fill}题，
                    简答题{selectedTemplate.questionTypes.essay}题
                  </p>
                </div>
              }
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<RobotOutlined />}>
                开始生成
              </Button>
              <Button onClick={() => setGenerateModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 生成进度模态框 */}
      <Modal
        title="正在生成试卷"
        open={isGenerating}
        footer={null}
        closable={false}
        width={500}
      >
        <div style={{ textAlign: "center", padding: "20px" }}>
          <Progress
            type="circle"
            percent={generationProgress}
            format={percent => `${percent}%`}
            size={120}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
          <div style={{ marginTop: 20 }}>
            <Text strong>正在使用AI生成试卷，请稍候...</Text>
          </div>
          
          {/* 进度阶段提示 */}
          <div style={{ marginTop: 10, fontSize: "14px", color: "#666" }}>
            {generationProgress < 5 && "正在分析模板要求..."}
            {generationProgress >= 5 && generationProgress < 90 && "正在生成题目..."}
            {generationProgress >= 90 && generationProgress < 100 && "正在完成最终处理..."}
            {generationProgress === 100 && "生成完成！"}
          </div>
          
          {/* 题目统计 */}
          {generatingPaper && (
            <div style={{ marginTop: 15 }}>
              <div style={{ fontSize: "12px", color: "#666", marginBottom: 5 }}>
                试卷信息：{generatingPaper.name}
              </div>
              {generatingPaper.questions && (
                <div style={{ fontSize: "12px", color: "#666" }}>
                  已生成 {generatingPaper.questions.length} 道题目
                </div>
              )}
              {selectedTemplate && (
                <div style={{ fontSize: "12px", color: "#666", marginTop: 5 }}>
                  模板：{selectedTemplate.name} | 难度：{selectedTemplate.difficulty}
                </div>
              )}
            </div>
          )}
          
          {/* 预计时间 */}
          {generationProgress > 0 && generationProgress < 100 && (
            <div style={{ marginTop: 10, fontSize: "11px", color: "#999" }}>
              预计剩余时间：{Math.max(1, Math.round((100 - generationProgress) / 10))} 秒
            </div>
          )}
        </div>
      </Modal>

      {/* 试卷预览模态框 */}
      <Modal
        title="试卷预览"
        open={previewModalVisible}
        onCancel={() => setPreviewModalVisible(false)}
        width={1000}
        footer={[
          <Button key="cancel" onClick={() => setPreviewModalVisible(false)}>
            关闭
          </Button>,
          <Button key="save" type="primary" onClick={handleSaveToExamManagement}>
            保存到考试管理
          </Button>,
          <Button key="export" onClick={handleExportPDF}>
            导出试卷PDF
          </Button>,
          <Button key="exportAnswer" onClick={handleExportAnswerPDF}>
            导出答案PDF
          </Button>,
        ]}
      >
        {previewPaper && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Title level={4}>{previewPaper.name}</Title>
              <Text>总分：{previewPaper.totalScore}分 | 时长：{previewPaper.duration}分钟 | 题目数：{previewPaper.questions?.length || 0}道</Text>
            </div>

            {previewPaper.questions?.map((question, index) => (
              <Card
                key={question.id}
                size="small"
                style={{ marginBottom: 16 }}
                title={`第${index + 1}题 (${(() => {
                  const typeMap = {
                    choice: "选择题",
                    programming: "编程题",
                    analysis: "分析题",
                    fill: "填空题",
                    essay: "简答题",
                  };
                  return typeMap[question.type];
                })()})`}
                extra={
                  <Space>
                    <Tag color="blue">{question.score}分</Tag>
                    <Tag color={question.difficulty === "简单" ? "green" : question.difficulty === "中等" ? "orange" : "red"}>
                      {question.difficulty}
                    </Tag>
                    {question.canRegenerate && (
                      <Button
                        type="link"
                        size="small"
                        icon={<ReloadOutlined />}
                        loading={regeneratingQuestion === question.id}
                        onClick={() => handleOpenRegenerateModal(question)}
                      >
                        重新生成
                      </Button>
                    )}
                    {question.regenerateCount && question.regenerateCount > 0 && (
                      <Badge count={question.regenerateCount} size="small" />
                    )}
                  </Space>
                }
              >
                <div style={{ marginBottom: 8 }}>
                  <Text strong>题目：</Text>
                  <Text>{question.content}</Text>
                </div>

                {question.type === "choice" && question.options && (
                  <div style={{ marginBottom: 8 }}>
                    <Text strong>选项：</Text>
                    <div style={{ marginLeft: 16 }}>
                      {question.options.map((option, optionIndex) => (
                        <div key={optionIndex}>
                          {String.fromCharCode(65 + optionIndex)}. {option}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div style={{ marginBottom: 8 }}>
                  <Text strong>答案：</Text>
                  <Text>{question.answer}</Text>
                </div>

                {question.analysis && (
                  <div>
                    <Text strong>解析：</Text>
                    <Text>{question.analysis}</Text>
                  </div>
                )}
              </Card>
            ))}
          </div>
        )}
      </Modal>

      {/* 题目重新生成模态框 */}
      <Modal
        title="重新生成题目"
        open={regenerateModalVisible}
        onCancel={() => setRegenerateModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={regenerateForm}
          layout="vertical"
          onFinish={handleRegenerateQuestion}
        >
          <Form.Item
            name="questionType"
            label="题目类型"
          >
            <Input disabled />
          </Form.Item>

          <Form.Item
            name="originalContent"
            label="原题目内容"
          >
            <TextArea rows={3} disabled />
          </Form.Item>

          <Form.Item
            name="requirements"
            label={
              <span>
                重新生成要求
                <Tooltip title="请详细描述您希望重新生成的题目应该具备的特点和要求">
                  <QuestionCircleOutlined style={{ marginLeft: 8 }} />
                </Tooltip>
              </span>
            }
            rules={[{ required: true, message: "请输入重新生成要求" }]}
          >
            <TextArea
              rows={4}
              placeholder="例如：希望题目更贴近实际应用场景，增加代码示例，提高难度，或者改变题目风格..."
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<RobotOutlined />}>
                开始重新生成
              </Button>
              <Button onClick={() => setRegenerateModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TemplateManagement; 





